package com.budwk.app.sqfwV2.generator.dayingRoadExcel;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.component.DictComponent;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.bo.SqfwExcelJudgeRes;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.component.FireIssusComponent;
import com.budwk.app.sqfwV2.component.ProblemComponent;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.AccommodatePeopleVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.template.GreatRiskHiddenExcelVo;
import com.budwk.app.sqfwV2.dto.image.FireSafetyOnDayingRoadExcelImageConfigBO;
import com.budwk.app.sqfwV2.enums.DayingRoadFileServiceEnum;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 4 消防安全重大风险隐患专项整治附件1.xlsx	----云岩区消防安全重大风险隐患专项排查整治进度统计表.xlsx
 */

@Slf4j
public class GreatRiskHiddenGenerator extends BaseTemplateExcelGenerator implements DayingRoadExcelGenerator {

    @Override
    protected String getTemplateName() {
        return DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_FIRE.getFilePath();
    }

    /**
    * 可以参照 {@link com.budwk.app.sqfw.enums.DownLoadFileNameEnum}
    *
    * @return 文件名名称
    */
    @Override
    public String getDownloadFileName() {
        return DayingRoadPdfComponent.getDictName(DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_FIRE.getCode(), null);
    }

    /**
     * 用户自定义excel基础参数，比如表头这样的公用数据
     * @param excelParam 已经填充的基础数据据
     * @param excelCreateParam excel生成提供的原料
     */
    @Override
    protected void customerPopularSheetBaseParam(Map<String, Object> excelParam, SqfwExcelCreateCommonBO excelCreateParam) {
        excelParam.put("district", DayingRoadPdfComponent.getDistrict(excelCreateParam.getBaseExcelParamDTO().getDistrict()));
    }

    /**
     * 构建表体特殊数据
     * @param listMap
     * @param excelCreateParam
     */
    @Override
    protected void customerPopularSheetDataParam(List<Map<String, Object>> listMap, SqfwExcelCreateCommonBO excelCreateParam) {
        List<Sqfw_formSummary_new> summaryList = DayingRoadPdfComponent.getSummaryList(listMap, excelCreateParam);
        List<Sqfw_formSummary_new> checkDatas = new ArrayList<>();
        for (Sqfw_formSummary_new summary : summaryList) {
            FireSafetyOnDayingRoadPdfDTO roadPdfDTO = JSONObject.parseObject(summary.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
            log.info("GreatRiskHiddenGenerator customerPopularSheetDataParam roadPdfDTO: {}", JSONObject.toJSONString(roadPdfDTO));
            if (!isGenerateExcel(roadPdfDTO)) {
                continue;
            }
            checkDatas.add(summary);
        }
        // 构建对象
        String county = excelCreateParam.getBaseExcelParamDTO().getCounty();
        GreatRiskHiddenExcelVo excelVo = buildGreatRiskHiddenExcelVo(checkDatas);
        excelVo.setCounty(county);
        listMap.add(CommonComponent.entityToMap(excelVo));
        log.info("GreatRiskHiddenGenerator customerPopularSheetDataParam end: {}", JSONObject.toJSONString(listMap));
    }

    /**
     * ●生成表格注意事项：
     * ○暂时只生成（三合一）一栏。
     * ○【是否住人】状态不为【否】时，生成该表格。
     * ○注：后期后台会根据区域和时间来生成。
     */
    public boolean isGenerateExcel(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        // 判断a5是否为重点场所 选择重点场所 不生成表格
        if (DayingRoadPdfComponent.isKeyLocations(roadPdfDTO)) {
            return false;
        }
        // 是否住人
//        return DayingRoadPdfComponent.isAccommodatePeople(roadPdfDTO.getAccommodatePeople());
        return true;
    }

    private GreatRiskHiddenExcelVo buildGreatRiskHiddenExcelVo(List<Sqfw_formSummary_new> formSummaryNews) {
        Set<String> peersSet = Sets.newHashSet(); // 出动人员名称set
        int findDangerThreeTotal = 0; //  整治小型生产经营场所（三合一）->发现隐患处数（处）
        int recDangerTotal = 0; //  整治小型生产经营场所（三合一）->整改隐患处数（处）
        int cleanIllegalThreeTotal = 0; //  整治小型生产经营场所（三合一）->清理违规留宿人员（家）
        for (Sqfw_formSummary_new formSummaryNew : formSummaryNews) {
            String paramData = formSummaryNew.getParamData();
            FireSafetyOnDayingRoadPdfDTO roadPdfDTO = JSONObject.parseObject(paramData, FireSafetyOnDayingRoadPdfDTO.class);
            // 出动人数 同行人+提交人
            if (StringUtils.isNotEmpty(formSummaryNew.getCreateBy())) peersSet.add(formSummaryNew.getCreateBy());
            if (StringUtils.isNotBlank(roadPdfDTO.getPeers())) {
                peersSet.addAll(Sets.newHashSet(Splitter.on(",").split(roadPdfDTO.getPeers())));
            }
            AccommodatePeopleVo a = roadPdfDTO.getAccommodatePeople();
            if (a != null) {
                if (DictConstants.RESIDENTS_FORM_RECTIFIED.equals(a.getResidentialType())) {
                    Boolean isRectification = a.getIsRectification();
                    if (isRectification != null && isRectification) recDangerTotal ++;
                    if (isRectification != null && isRectification) cleanIllegalThreeTotal ++;
                }
            }
            if (!isCalcuate(roadPdfDTO)) {
                continue;
            }
            // 发现隐患处数（处）  只计算住人的情况
            // 整改隐患处数（处）
            if (a != null) {
                Boolean isRectification = a.getIsRectification();
                if (isRectification != null) findDangerThreeTotal ++;
                if (isRectification != null && isRectification) recDangerTotal ++;
                if (isRectification != null && isRectification) cleanIllegalThreeTotal ++;
            }
        }
        peersSet.remove("");
        GreatRiskHiddenExcelVo excelVo = new GreatRiskHiddenExcelVo();
        excelVo.setCheckPersonCount(peersSet.size())
                .setCompaneyThreeCount(formSummaryNews.size())
                .setRecDangerThreeTotal(recDangerTotal)
                .setCleanIllegalThreeTotal(cleanIllegalThreeTotal)
                .setFindDangerThreeTotal(findDangerThreeTotal)
                .setNum(1);
        return excelVo;
    }

    /**
     * 是否参与计算
     *  住人形式为：前店后住，下店上住，夹层住人，其他时，如果是旅馆，不参与计算，否则参与计算
     */
    private boolean isCalcuate(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        if (DictConstants.MAIN_BUSINESS_SCOPE_HOTEL.equals(roadPdfDTO.getMainBusinessScope())) {
            return false;
        }
        return FireIssusComponent.existAccommodatePeopleProblem(roadPdfDTO);
    }

    /**
     * 是否整治小型生产经营场所（三合一）->发现隐患处数（处）
     * 统计住人形式
     *  灭火器 电器线路情况  电动自行车使用情况  是否使用明火、高温加热、取暖设备等的使用地点
     *  是否存放易燃易爆危险品
     * @return true:有隐患  false:无隐患
     */
    private boolean isFindDangerThree(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        // 1 住人形式
        AccommodatePeopleVo a = roadPdfDTO.getAccommodatePeople();
        if (a != null) {
            Boolean isRectification = a.getIsRectification();
            if (isRectification != null) {
                return true;
            }
        }
        // 2 灭火器
        if (ProblemComponent.isHiveDanger(roadPdfDTO.getWhetherEquippedFire())) {
            return true;
        }
        // 3 电气线路情况
        if (ProblemComponent.isHiveDanger(roadPdfDTO.getElectricalCircuitSituation())) {
            return true;
        }
        // 4 电动自行车使用情况
        if (ProblemComponent.isHiveDanger(roadPdfDTO.getElectricBicyclesUse())) {
            return true;
        }
        // 5 明火、高温加热、取暖设备等的使用地点
        if (ProblemComponent.isHiveDanger(roadPdfDTO.getFireHighUsageArea())) {
            return true;
        }
        // 6 是否存放易燃易爆危险品
        if (ProblemComponent.isHiveDanger(roadPdfDTO.getIsCombustiblEexplosive())) {
            return true;
        }
        return false;
    }

    private boolean checkProblem(SafeCheckTaskParamDataDTO p, boolean bValue) {
        if (p != null) {
            return p.getKey().equals(String.valueOf(bValue));
        }
        return false;
    }

    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParam) {

    }

    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, SqfwExcelForSummaryBO forSummaryBO) {

    }

    /**
     * 如果在遍历之前就能够判断excel是否生成，那么就在这个方法中进行判断
     * @param excelCreateParam excel生成所需的最为全面的数据
     * @param excelParam excel已经填充的部分数据
     */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeErgodic(SqfwExcelCreateCommonBO excelCreateParam, Map<String, Object> excelParam) {
        return DayingRoadPdfComponent.getSqfwExcelJudgeRes(excelCreateParam, new GreatRiskHiddenGenerator());
    }

    /**
     * 如果在遍历之后能够判断excel是否生成，那么就在这个方法中进行判断
     * @param excelParam excel已经填充的部分数据
     */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeCreate(Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected Class<?> getImageConfigBO() {
        return FireSafetyOnDayingRoadExcelImageConfigBO.class;
    }
}
